﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

using SqlSugar;
using App.Helper;
using App.Model.ReturnModel;

namespace App.Repository
{
    public abstract class BaseDAL<T> where T : class, new()
    {
        public SqlSugarClient db;
        public SimpleClient sdb;

        public BaseDAL()
        {
            db = SqlSugarHelper.GetClient();
            sdb = db.GetSimpleClient();
        }

        #region CRUD
        public TableModel<T> GetPageList(Expression<Func<T, bool>> ex, int pageIndex, int pageSize, Expression<Func<T, object>> orderByExpression = null, OrderByType orderByType = OrderByType.Asc)
        {
            PageModel p = new PageModel() { PageIndex = pageIndex, PageSize = pageSize };
            List<T> data = sdb.GetPageList(ex, p, orderByExpression, orderByType);
            var t = new TableModel<T>
            {
                Recode = 1,
                Count = p.PageCount,
                Data = data,
                Msg = "成功"
            };
            return t;
        }

        public T Get(long id)
        {
            return sdb.GetById<T>(id);
        }

        public bool Add(T entity)
        {
            return sdb.Insert(entity);
        }

        public bool Update(T entity)
        {
            return sdb.Update(entity);
        }

        public bool Dels(dynamic[] ids)
        {
            return sdb.DeleteByIds<T>(ids);
        }
        #endregion

        public T GetMaxEntiy(Expression<Func<T, bool>> where, Expression<Func<T, object>> order)
        {
            return db.Queryable<T>().Where(where).OrderBy(order, OrderByType.Desc).First();
        }

        public T GetByWhere(Expression<Func<T, bool>> where)
        {
            return db.Queryable<T>().Where(where).First();
        }
    }
}
